/*
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2024-02-29 14:51:17
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-09-13 20:11:07
 * @FilePath: \electron-demo\electron\main.js
 * @Description: electron 主入口
 */
const { app, BrowserWindow, systemPreferences, ipcMain } = require('electron')
// import { app, BrowserWindow } from 'electron'
const path = require('node:path')
const url = require('url')
// import path from 'path'
// import { fileURLToPath } from 'node:url'
// import { dirname } from 'node:path'

//const isDev = require('electron-is-dev')
//import isDev from 'electron-is-dev'
const PROTOCOL = 'ai-doctor'
/** BrowserWindow实例 */
let window = null

const createWindow = async () => {
  window = new BrowserWindow({
    width: 440,
    height: 800,
    frame: false, // 去掉顶部导航、关闭按钮、最大化最小化按钮
    webPreferences: {
      //nodeIntegration: true,
      //contextIsolation: false,
      preload: path.join(__dirname, '../electron/preload.js')
    }
  })
  // 此处调用并授权（麦克风、摄像头等）
  await checkMediaAccess('microphone')
  if (!app.isPackaged) {
    window.loadURL('http://localhost:5000')
  } else {
    //window.loadFile('./dist/index.html')
    window.loadFile(path.join(__dirname, '../dist/index.html'))
  }
  window.setMenu(null) // 顶部菜单
  // window.webContents.openDevTools() // 开启调试工具

  // 当窗口关闭时释放资源
  window.on('closed', () => {
    window = null;
  });

  ipcMain.on('window-show', () => window.show())
  ipcMain.on('window-hide', () => window.hide())
  ipcMain.on('window-min', () => window.minimize())
  ipcMain.on('window-max', () => window.maximize())
  ipcMain.on('window-close', () => window.close())
}

// 当应用启动完成后，主动判断应用是否是从网页中调起
const _handleAfterReady = () => {
  // windows如果是通过url schema启动则发出时间处理
  // 启动参数超过1个才可能是通过url schema启动
  if (process.argv.length > 1) {
    if (!app.isReady()) {
      app.once('browser-window-created', () => {
        // app 未打开时，通过 open-url打开 app，此时可能还没 ready，需要延迟发送事件
        // 此段ready延迟无法触发 service/app/ open-url 处理，因为saga初始化需要时间
        app.emit('second-instance', null, process.argv)
      })
    } else {
      app.emit('second-instance', null, process.argv)
    }
  }
}

const secondInstance = (params) => {
  // 使用 url 模块解析 URL
  const parsedUrl = url.parse(params?.[params.length - 1], true);
  // 获取查询参数
  const queryParams = parsedUrl.query;
  
  if (window) {
    // 当最小化的时候
    if (window.isMinimized()) {
      window.restore()
    }
    window.focus()

    /** 向渲染进程传参 */
    window.webContents.send('awaken', queryParams)
  }
}

// 如果有实例在运行了，直接退出
const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
  app.quit()
} else {
  /** Windows */
  app.on('second-instance', async (event, argv) => {
    secondInstance(argv)
  })

  /** Mac */
  app.on('open-url', (event, url) => {
    event.preventDefault()
    secondInstance(url)
  })

  app.whenReady().then(() => {
    createWindow()
    app.on('activate', () => {
      if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })

    /** 注册伪协议 */
    app.setAsDefaultProtocolClient(PROTOCOL)
    _handleAfterReady()
  })

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
  })
}
// 权限授权
async function checkMediaAccess(mediaType) {
  const result = systemPreferences.getMediaAccessStatus(mediaType)
  //await BrowserWindow.mediaDevices.getUserMedia({ audio: true }) //TODO
  if (result !== 'granted') {
    await systemPreferences.askForMediaAccess('microphone')
  }
}

/*
--Tip
window当前目录: electron-demo根目录
__dirname: electron-demo/electron
*/
